package com.butnet.myframe.ajax;

import java.io.UnsupportedEncodingException;

public class AjaxParameter {
	public static String ajaxTo(String ajax) {
		if (ajax == null)
			return null;
		char[] chs = ajax.toCharArray();
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < chs.length;) {
			if (chs[i] == '%') {
				i++;
				if (i < chs.length) {
					if (chs[i] == 'U' || chs[i] == 'u') {
						i++;
						char[] uxxxx = new char[4];
						uxxxx[0] = chs[i++];
						uxxxx[1] = chs[i++];
						uxxxx[2] = chs[i++];
						uxxxx[3] = chs[i++];
						char c = (char) Integer.parseInt(new String(uxxxx), 16);
						str.append(c);
					} else {
						char[] xx = new char[2];
						xx[0] = chs[i++];
						xx[1] = chs[i++];
						char c = (char) Integer.parseInt(new String(xx), 16);
						str.append(c);
					}
				} else {
					str.append('%');
				}
			} else {
				str.append(chs[i]);
				i++;
			}
		}
		return str.toString();
	}

	public static String ajaxToURL(String ajax) throws UnsupportedEncodingException {
		if (ajax == null)
			return null;
		char[] chs = ajax.toCharArray();
		byte[] bs = new byte[chs.length];
		int len = 0;
		for (int i = 0; i < chs.length;) {
			if (chs[i] == '%') {
				i++;
				char[] uxxxx = new char[2];
				uxxxx[0] = chs[i++];
				uxxxx[1] = chs[i++];
				bs[len++]=(byte)Integer.parseInt(new String(uxxxx), 16);
			} else {
				bs[len++]=Byte.valueOf((byte)chs[i]);
				i++;
			}
		}
		return new String(bs,0,len,"UTF-8");
	}
}
